import axios, { AxiosResponse } from 'axios';
import { handleApiError } from './errorHandler';

// 创建一个自定义的 axios 实例
const request = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/api/v1': process.env.REACT_APP_API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
});

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token && !config.headers.Authorization) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  error => handleApiError(error),
);

export { request };